/*
 * @Author: 糊涂的老知青
 * @Date: 2022-09-01
 * @Version: 1.0.0
 * @Description:
 */
package httpclient

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"
)

func HttpGet(apiUrl string, headers map[string]string) (int, string, error) {
	client := &http.Client{}
	req, _ := http.NewRequest("GET", apiUrl, nil)
	for k, v := range headers {
		req.Header.Add(k, v)
	}
	rsp, err := client.Do(req)
	if err != nil {
		return rsp.StatusCode, "", err
	}
	body, _ := ioutil.ReadAll(rsp.Body)
	bodyAsString := string(body)
	if rsp.StatusCode >= 300 || rsp.StatusCode < 200 {
		return rsp.StatusCode, bodyAsString, err
	}
	return rsp.StatusCode, bodyAsString, nil
}

func HttpPost(apiUrl string, headers map[string]string, data map[string]interface{}) (int, string, error) {
	client := &http.Client{}
	bytesData, _ := json.Marshal(data)
	req, _ := http.NewRequest("POST", apiUrl, bytes.NewReader(bytesData))
	for k, v := range headers {
		req.Header.Add(k, v)
	}
	rsp, err := client.Do(req)
	if err != nil {
		return rsp.StatusCode, "", err
	}
	body, _ := ioutil.ReadAll(rsp.Body)
	bodyAsString := string(body)
	if rsp.StatusCode >= 300 || rsp.StatusCode < 200 {
		return rsp.StatusCode, bodyAsString, err
	}
	return rsp.StatusCode, bodyAsString, nil
}
